import { useEffect, useRef } from 'react'
import { useAppDispatch, useAppSelector } from '@/store'
import type { AsyncAction, RootState } from '@/types/store'

/**
 * 获取redux中数据的初始状态
 * @param action 异步action
 * @param sliceName chunk名字
 * @returns
 */
function useInitialState<K extends keyof RootState>(action: AsyncAction, sliceName: K, data?: any) {
  const dispatch = useAppDispatch()
  const state = useAppSelector((state: RootState) => state[sliceName])
  const renderRef = useRef(true)
  async function execDispatch() {
    await dispatch(action(data))
    renderRef.current = true
  }
  useEffect(() => {
    if (renderRef.current) {
      renderRef.current = false
      execDispatch()
    }
  }, [dispatch, action])
  return state
}

export { useInitialState }
